#include "network_manager.h"
#include "esp_log.h"
#include "at_parser.h"  // 自定义AT指令解析器

static const char* TAG = "NetMgr";
static network_type_t active_network = NETWORK_TYPE_NONE;

// WiFi事件处理（简化版）
static void wifi_event_handler(void* arg, esp_event_base_t event_base, 
                            int32_t event_id, void* event_data) {
    if (event_id == WIFI_EVENT_STA_CONNECTED) {
        active_network = NETWORK_TYPE_WIFI;
    } else if (event_id == WIFI_EVENT_STA_DISCONNECTED) {
        if (active_network == NETWORK_TYPE_WIFI) {
            start_cellular_backup();
        }
    }
}

// 启动蜂窝备份连接
static void start_cellular_backup() {
    ESP_LOGI(TAG, "Attempting cellular connection...");
    if (at_send_command("AT+NETOPEN") == AT_OK) {
        active_network = NETWORK_TYPE_CELLULAR;
        ESP_LOGI(TAG, "Cellular connected via Air780");
    }
}

void network_init() {
    // 初始化WiFi（略）
    esp_event_handler_register(WIFI_EVENT, ESP_EVENT_ANY_ID, wifi_event_handler, NULL);
    
    // 初始化Air780串口
    uart_config_t uart_conf = {
        .baud_rate = 115200,
        .data_bits = UART_DATA_8_BITS,
        .parity = UART_PARITY_DISABLE,
        .stop_bits = UART_STOP_BITS_1
    };
    uart_param_config(UART_NUM_1, &uart_conf);
    uart_driver_install(UART_NUM_1, 2048, 0, 0, NULL, 0);
}

int network_send(const char* data, size_t len) {
    switch (active_network) {
        case NETWORK_TYPE_WIFI:
            return esp_http_client_send(data, len);
        case NETWORK_TYPE_CELLULAR:
            char cmd[256];
            snprintf(cmd, sizeof(cmd), "AT+SEND=%d\r\n%s", len, data);
            return at_send_command(cmd) == AT_OK ? len : -1;
        default:
            return -1; // 无可用网络
    }
}
